package com.cefa.edu.service;

import com.cefa.edu.dao.GradeMapper;
import com.cefa.edu.dao.OrganRelationMapper;
import com.cefa.edu.dao.PhaseMapper;
import com.cefa.edu.dao.UserOrganRoleMapper;
import com.cefa.edu.pojo.Grade;
import com.cefa.edu.pojo.Phase;
import com.google.common.base.Strings;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * Created by cc664 on 2018/8/10.
 */
@Service
public class PhaseService{
    @Autowired
    private PhaseMapper phaseMapper;
    @Autowired
    private GradeMapper gradeMapper;
    @Autowired
    private OrganRelationMapper organRelationMapper;

    @Autowired
    private UserOrganRoleMapper userOrganRoleMapper;

    //静态集合 缓存学习阶段、年级排序数据
    private static  Map<String,Integer> organSortMap=null;
    static {
        organSortMap=new HashMap<String,Integer>();
        //学习阶段
        organSortMap.put("幼儿园",1);
        organSortMap.put("小学",2);
        organSortMap.put("初中",3);
        organSortMap.put("高中",4);

        //高中年级
        organSortMap.put("高一",1);
        organSortMap.put("高二",2);
        organSortMap.put("高三",3);
        //初中年级
        organSortMap.put("初一",1);
        organSortMap.put("初二",2);
        organSortMap.put("初三",3);
        //小学年级
        organSortMap.put("一年级",1);
        organSortMap.put("二年级",2);
        organSortMap.put("三年级",3);
        organSortMap.put("四年级",4);
        organSortMap.put("五年级",5);
        organSortMap.put("六年级",6);
        //幼儿园年级
        organSortMap.put("小班",1);
        organSortMap.put("中班",2);
        organSortMap.put("大班",3);
        organSortMap.put("学前",4);
    }


    /**
     * @aa 根据机构名称 获取对应的sort值
     * @aa add by chaijian 2018-08-17
     */
    public Map<String,Integer> getSortValueByOrgans(String organNames){
       //初始化 organSortMap集合数据
       if(Strings.isNullOrEmpty(organNames)){
           return  null;
       }else {
          String[] organNameArr= organNames.split(",");
          if(organNameArr!=null && organNameArr.length>0){
              Map<String,Integer> nameSortMap=new HashMap<String,Integer>();

              //把机构名称和机构sort值 存储到map中
              for(String organName:organNameArr){
                  nameSortMap.put(organName,Integer.parseInt(organSortMap.get(organName).toString()))  ;
              }
              return nameSortMap;
          }
       }

        return null;
    };

    /**
     * @aa 根据学习id 获取对应的学习阶段数据
     * @aa 参数：学校id
     * @aa add by chaijian 2018-08-10
     */
    public List<Phase> getPhasesBySchoolId(Integer schoolId){
       return phaseMapper.findPhaseListBySchoolId(schoolId);
    }

    /**
     * @aa 添加学习阶段及阶段下的年级数据及关系表数据(组织机构关系表,用户角色组织机构关系表)
     * @aa add by chaijian 2018-08-10
     */
    @Transactional
    public Integer savePhaseAndGrades(Phase phase, String name,Integer userId,Integer roleType,String gradeSorts){

        //计算该学习阶段下的年级个数 封装到phase对象中
        String[] gradeNames=name.split(",");
        //设置该阶段下年级个数
        phase.setGradeCount(gradeNames.length);
        //添加学习阶段数据到DB中
        phaseMapper.savePhase(phase);

        //组织数据封装到grade中
        List<Grade> gradeList=this.getGradesWith(gradeNames,phase,StringUtils.isNotBlank(gradeSorts)?gradeSorts:null);
        //添加年级数据到DB中
        List<Integer>gradeIdList=new ArrayList<Integer>();
        for(Grade grade:gradeList){
            int res=gradeMapper.saveGrades(grade);
            gradeIdList.add(grade.getId());
        }

        //组织批量添加组织架构关系表数据
       String organValues=organizeOrganRelationInsertValues(phase,gradeIdList);
        //添加数据到组织架构关系表中
       organRelationMapper.saveOrganRelation(organValues);

       //添加用户组织架构角色关系表数据
        int res=userOrganRoleMapper.saveUserOrganRoleForAdmin(userId,phase.getSchoolId(),phase.getId(),roleType);
       /*
        String userOrganRoleValues=organizeUserOrganRoleInsertValues(phase,gradeIdList,userId,roleType);
        //添加数据到用户组织机构角色关系表
       int res= userOrganRoleMapper.saveUserOrganRole(userOrganRoleValues);
      */

      return res;
    }

    //组织批量添加用户组织架构角色关系表数据
    private String organizeUserOrganRoleInsertValues(Phase phase, List<Integer> gradeIdList, Integer userId, Integer roleType) {
        StringBuffer values=new StringBuffer(" ");
        for(Integer id:gradeIdList){
            values.append("(");
            values.append(userId+",");
            values.append(phase.getSchoolId()+",");
            values.append(phase.getId()+",");
            values.append(id+",");
            values.append(roleType);
            values.append("),");
        }

        //去除最后一个字符","
        values=values.deleteCharAt(values.length()-1);
        return values.toString();

    }

    //组织数据封装到grade中
    private List<Grade> getGradesWith(String[] gradeNames, Phase phase,String gradeSorts) {

        List<Grade>gradeList=new ArrayList<Grade>();
        int correntYear = Calendar.getInstance().get(Calendar.YEAR);//当前年
        int sort=0;
        Grade grade=null;
        String gname=null;
        String[]sortArr=null;
        if(StringUtils.isNotBlank(gradeSorts)){
            sortArr=gradeSorts.split(",");
        }
        for(int i=0;i<gradeNames.length;i++){
            gname=gradeNames[i];

            grade=new Grade();
            grade.setGradeName(gname);
            if(StringUtils.isNotBlank(gradeSorts)){
                sort=Integer.parseInt(sortArr[i]);
                grade.setSort(sort);
            }else {
                grade.setSort(++sort);
            }
            grade.setSchoolId(phase.getSchoolId());
            grade.setGradeDate(correntYear--);
            grade.setType(phase.getId());
            gradeList.add(grade);
        }
        /*
        for(String gname:gradeNames){
            grade=new Grade();
            grade.setGradeName(gname);
            grade.setSort(++sort);
            grade.setSchoolId(phase.getSchoolId());
            grade.setGradeDate(correntYear--);
            grade.setType(phase.getId());
            gradeList.add(grade);
        }*/

        return gradeList;
    }

    //组织批量添加的组织架构关系数据的values值
    private String organizeOrganRelationInsertValues( Phase phase, List<Integer>gradeIdList) {
        StringBuffer values=new StringBuffer(" ");
        for(Integer id:gradeIdList){
            values.append("(");
            values.append(phase.getSchoolId()+",");
            values.append(phase.getId()+",");
            values.append(id);
            values.append("),");
        }

        //去除最后一个字符","
        values=values.deleteCharAt(values.length()-1);
        return values.toString();
    }

    /**
     * @aa 根据教育学习阶段id 删除对应的数据
     * @param phaseId
     */
    @Transactional
    public void deletePhase(Integer phaseId) {
       organRelationMapper.deleteOrganRelationByPhaseId(phaseId);
        phaseMapper.deletePhaseById(phaseId);
        userOrganRoleMapper.deleteUserOrganRoleByPhaseId(phaseId);
    }
}
